package com.tianhe.visitormanagement.server.impl;

import com.tianhe.device.domain.VisitorMachine;
import com.tianhe.device.feign.RemoteVisitorMachineService;
import com.tianhe.visitormanagement.server.common.UdpServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @Author ：dongchao
 * @Date ：Created in 11:00 2022/3/7
 */
@Slf4j
@Component
public class UdpServerImpl extends UdpServer {

    @Autowired
    private RemoteVisitorMachineService remoteVisitorMachineService;

    @Override
    public void heartbeat() {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Object object = remoteVisitorMachineService.list(new VisitorMachine()).get("row");
                if (object == null && CollectionUtils.isEmpty((List<VisitorMachine>) object)) {
                    return;
                }
                List<VisitorMachine> visitorMachineList = (List<VisitorMachine>) object;
                visitorMachineList.stream().forEach(s -> {
                    s.setStatus(isServerOpen(s.getIp()) ? 1L : 2L);
                    remoteVisitorMachineService.editSave(s);//更新设备状态
                });
            }
        }, 5000, 5000);
    }
}
